package net.israfil.mojo.flex2;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.dependency.AbstractFromDependenciesMojo;
import org.apache.maven.plugin.dependency.utils.DependencyStatusSets;
import org.apache.maven.plugin.dependency.utils.filters.ArtifactsFilter;
import org.apache.maven.plugin.dependency.utils.filters.DestFileFilter;
import org.apache.maven.project.MavenProject;

/**
 * Goal that copies the project dependencies from the repository to a defined
 * location.
 * 
 * @author brianf (copied and modified)
 * @author <a href="mailto:cgruber@israfil.net">Christian Edward Gruber</a>
 * @goal copy-flex-applications
 * @requiresDependencyResolution test
 * @phase process-resources
 * 
 */
public class CopyModulesMojo extends AbstractFromDependenciesMojo {

    /**
     * The modules which will be copied from dependencies
     *
     * @parameter
     * @required
     */
    private List modules;

    /**
     * POM
     * 
     * @parameter expression="${project}"
     * @readonly
     * @required
     */
    private MavenProject internalProject;
    
    /**
     * target folder
     * 
     * @parameter expression="${project.build.directory}"
     * @readonly
     * @required
     */
    private File buildDirectory;

    /**
     * Main entry into mojo. Gets the list of dependencies and iterates through
     * calling copyArtifact.
     * 
     * @throws MojoExecutionException
     *             with a message if an error occurs.
     * 
     * @see #getDependencies
     * @see #copyArtifact(Artifact, boolean)
     */
    public void execute() throws MojoExecutionException, MojoFailureException { 
    	getLog().debug("Build Directory: " + buildDirectory);
    	getLog().debug("Project file: " + project);			// FIXME: Why not!?!?!?!
    	getLog().debug("Project file: " + internalProject);	// FIXME: Why?!?!?!?!
    	project = internalProject;
        DependencyStatusSets dss = getDependencySets( true );
        Set artifacts = dss.getResolvedDependencies();
        if (modules == null || modules.size() == 0) {
        	getLog().warn("No flex modules defined - plugin will do nothing.");
        } else {
        	for (Iterator modulesI = modules.iterator(); modulesI.hasNext(); ) {
	        	FlexModule module = (FlexModule)modulesI.next();	
	        	getLog().debug("Processing Module: " + module);
	    		module.resolveArtifact(getProject(), artifacts);
        		Artifact a = module.getArtifact();
        		getLog().debug("Processing Module Artifact: " + a);
	    		File fullTarget = getFullTarget(module);
        		File targetFile = new File(fullTarget, module.getTargetFilename());
        		getLog().debug("Copying module to " + targetFile.getAbsolutePath());
        		copyFile( a.getFile(), targetFile );
	        } 
        }
    }
    
    private File getFullTarget(FlexModule module) throws MojoFailureException {
		if (module.getTargetPath() == null || 
				module.getTargetPath().equals(".") || 
				module.getTargetPath().equals(".."))
    			throw new MojoFailureException("Inappropriate target folder: " + module.getTargetPath());
		File file =  new File(module.getTargetPath());
    	if (! file.isAbsolute()) // replace with folder relative to basedir to match war.
    		file = new File(project.getBasedir(), module.getTargetPath());
		if (!file.exists()) file.mkdir();
		getLog().debug("Full target folder = " + file.getPath());
		return file;
    }

    protected ArtifactsFilter getMarkedArtifactFilter() {
        return new DestFileFilter( this.overWriteReleases, this.overWriteSnapshots, this.overWriteIfNewer,
                                   this.useSubDirectoryPerArtifact, this.useSubDirectoryPerType, 
                                   this.useRepositoryLayout, false, this.buildDirectory );
    }
}
